<?php
namespace app\plus\controller;

use think\Controller;
use think\Cookie;
use think\Request;

class WxHelperController extends Controller
{

    private $options;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->options=config('wechat');
    }

    /**
     * 获取openid并返回来源页面
     * @throws \Exception
     */
    public function getOpenid(){
        $oauth = & load_wechat('Oauth',$this->options);
        if(isset($_GET['code'])){
            $result = $oauth->getOauthAccessToken();
            if($result===FALSE){
                exception($oauth->errMsg,40001);
            }else{
                $wxuser = $oauth->getOauthUserinfo($result['access_token'], $result['openid']);
                //处理返回结果
                if($wxuser===FALSE){
                    exception($oauth->errMsg,40001);
                }else{
                    $referer=Cookie::get('wx_referer');
                    cookie::set('wxuser',$wxuser);
                    Cookie::delete('wx_referer');
                    $this->redirect($referer);
                }
            }
        }else{
            $referer = urldecode($this->request->param('referer',null,null));
            Cookie::set('wx_referer',$referer);
            $callback = $this->request->url(true); //当前地址
            // 执行接口操作
            $redirect = $oauth->getOauthRedirect($callback, 1, 'snsapi_userinfo');
            if($redirect===FALSE){
                exception($oauth->errMsg,40001);
            }else{
                $this->redirect($redirect);
            }
        }
    }

}